#!/bin/sh
set -e

PREREQ=""

prereqs() {
    echo "${PREREQ}"
}

case "$1" in
    prereqs)
        prereqs
        exit 0
        ;;
esac

# 可选：根据 /proc/cmdline 判断是否需要启用 verity
# 例如，你可以指定 verity_enable 参数控制
VERITY_ENABLE="yes"
for ARG in $(cat /proc/cmdline); do
    case "$ARG" in
        noverity)
            VERITY_ENABLE="no"
            ;;
        roothash=*)
            ROOTHASH="${ARG#roothash=}"
            ;;
    esac
done

if [ "$VERITY_ENABLE" != "yes" ]; then
    echo "dm-verity disabled by cmdline"
    exit 0
fi


# 加载必要模块
modprobe dm-verity || true

echo "Opening dm-verity rootfs..."

# 从环境变量获取UUID
ROOT_UUID="$rootuuid"
VERITY_UUID="$verityuuid"
ROOT_HASH="$roothash"

if [ -z "$ROOT_UUID" ] || [ -z "$VERITY_UUID" ]; then
    echo "Error: Missing required UUID environment variables"
    exit 1
fi

# 使用blkid查找对应的设备
# 注意：这里使用grep来查找包含特定UUID的设备
DATA_DEVICE=$(blkid | grep "UUID=\"$ROOT_UUID\"" | cut -d: -f1)
HASH_DEVICE=$(blkid | grep "UUID=\"$VERITY_UUID\"" | cut -d: -f1)
VERITY_NAME="root"

if [ -z "$DATA_DEVICE" ] || [ -z "$HASH_DEVICE" ]; then
    echo "Error: Could not find devices with specified UUIDs"
    echo "Root UUID: $ROOT_UUID"
    echo "Verity UUID: $VERITY_UUID"
    exit 1
fi

echo "Found devices:"
echo "Data device: $DATA_DEVICE"
echo "Hash device: $HASH_DEVICE"


# 执行 veritysetup
veritysetup open "$DATA_DEVICE" "$VERITY_NAME" "$HASH_DEVICE" "$ROOT_HASH"

echo "dm-verity rootfs opened in /dev/mapper/$VERITY_NAME"
